package com.edu.servlet;

import com.edu.bean.News;
import com.edu.service.UserNewsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/news")
public class UserNewsListServlet extends  HttpServlet {
    private UserNewsService newsService = new UserNewsService();
    private static final int PAGE_SIZE = 10;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取参数
        String category = request.getParameter("category");
        String pageStr = request.getParameter("page");

        // 参数验证
        if (category == null || category.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/user/home");
            return;
        }

        // 处理分页
        int page = 1;
        try {
            if (pageStr != null && !pageStr.trim().isEmpty()) {
                page = Integer.parseInt(pageStr);
                if (page < 1) {
                    page = 1;
                }
            }
        } catch (NumberFormatException e) {
            page = 1;
        }

        // 获取数据
        List<News> newsList = newsService.userGetNewsByCategory(category, page, PAGE_SIZE);
        int totalCount = newsService.userGetNewsTotalCount(category);
        int totalPages = (totalCount + PAGE_SIZE - 1) / PAGE_SIZE;

        // 设置属性
        request.setAttribute("newsList", newsList);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", totalPages);

        // 转发到列表页
        request.getRequestDispatcher("/user/news/list.jsp").forward(request, response);
    }

}